import pygame
import sys
import food as c_food
import snake as c_snake


def game_over():
    pygame.quit()
    sys.exit()


def game_start():
    window_title = 'Snake-AI'
    window_size = (640, 480)
    grid_num = (16, 12)                  # 64列，48行
    grid_size = (40, 40)

    pygame.init()
    pg_clock = pygame.time.Clock()

    main_window = pygame.display.set_mode(window_size)
    pygame.display.set_caption(window_title)

    FOOD = c_food.food()
    SNAKE = c_snake.snake()

    move_dir = 0                                # 0,1,2,3    上下左右
    whether_eat = 0                             # 0未吃，1吃了
    whether_die = 0                             # 0活着，1die

    body_list, not_body_list = SNAKE.init_body(grid_num)
    whether_eat, food_list = FOOD.make_food(1, not_body_list, [])

    while True:

        for event in pygame.event.get():

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and move_dir != 1:
                    move_dir = 0

                elif event.key == pygame.K_DOWN and move_dir != 0:
                    move_dir = 1

                elif event.key == pygame.K_LEFT and move_dir != 3:
                    move_dir = 2

                elif event.key == pygame.K_RIGHT and move_dir != 2:
                    move_dir = 3

            elif event.type == pygame.QUIT:
                game_over()

        not_body_list, body_list, whether_eat, whether_die = SNAKE.move_step(not_body_list, body_list, food_list, move_dir, grid_num)

        if whether_die == 1:
            body_list, not_body_list = SNAKE.init_body(grid_num)
            whether_eat, food_list = FOOD.make_food(1, not_body_list, [])
            whether_eat, whether_die = 0, 0

        whether_eat, food_list = FOOD.make_food(whether_eat, not_body_list, food_list)

        main_window.fill((0, 0, 0))

        FOOD.draw_food(food_list, main_window, grid_size)
        SNAKE.draw_body(body_list, main_window, grid_size)

        pygame.display.update()
        pg_clock.tick(5)


if __name__ == '__main__':
    game_start()